<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <title>相交/包含测试</title>
    <link rel="stylesheet" href="css/demo.css">
    <script src="js/configData.js"></script>


    <script src="libs/axios.min.js"></script>
    <script src="libs/httpService.js"></script>
    <script src="js/demo.js"></script>
</head>

<body>
<div id="map"></div>
<div class="opt_panel">
    <button onclick="start()">开始绘制</button>
    <button onclick="restore()">清空绘制</button>
    <br><br>
    <div class="opt_intro">
        点击按钮开始绘制,点击鼠标右键结束绘制;<br>结束后可以点击开始绘制再次绘制；
    </div>
</div>

<script>
    //示例说明：
    //本示例展示了杆线同步的应用场景，设备绘制总量不易超过200个（最好是及时将设备保存至服务端然后渲染到栅格上）


    //自定义示例参数


    var symbolLayer;

    var isDrawing = false

    //动态线对象
    var lineSymbol = null
    //预览用的符号
    var previewPointSymbol = null

    //鼠标移动的时候，实时更新线和预览符号对应的位置
    function onMouseMove(e) {
        //获取当前位置
        let movingPoint = [e.lngLat.lng, e.lngLat.lat]

        //更新点设备关联的线上对应节点的位置
        let lineGeom = lineSymbol.getGeometry()
        //最后一个位置是动态点
        lineGeom[0][lineGeom[0].length - 1] = movingPoint
        lineSymbol.setGeometry(lineGeom)
    }

    //鼠标点击设备时添加节点设备，同时更新线路末端的节点坐标
    function onAddDev(e) {
        let clickPoint = [e.lngLat.lng, e.lngLat.lat]
        let lineGeom = lineSymbol.getGeometry()
        //倒数第二个位置插入点
        lineGeom[0].splice(lineGeom[0].length - 1, 0, clickPoint)
        lineSymbol.setGeometry(lineGeom)
    }

    /**
     * 开始移动
     */
    function start() {
        if (!isDrawing) {
            restore()
            isDrawing = true
            map.getCanvas().style.cursor = 'crosshair'
            lineSymbol = new egisV2.symbol.EleLineSymbol({
                type: 'line',//类型point or line or fill
                devId: 'b20001' + Math.random(),//oid，psrid
                devTypeId: '35421985',//设备类型
                symbolId: '2010010',//符号ID
                symbolWidth: 20,//线宽
                symbolColor: '#ff0000',//颜色
                symbolOpacity: 1,//透明度
                coordinates: [
                    [[0, 0]]
                ],//坐标
                attributes: {c: 3, d: 4}//其它属性
            })
            symbolLayer.addEleDevs([lineSymbol])
            map.on('mousemove', onMouseMove)
            map.on('click', onAddDev)
            map.on('contextmenu', stop)
        }

    }

    /**
     * 停止绘制
     */
    function stop() {
        if (isDrawing) {
            let lineGeom = lineSymbol.getGeometry()
            //倒数第二个位置插入点
            lineGeom[0].pop()
            lineSymbol.setGeometry(lineGeom)
            isDrawing = false
            map.off('mousemove', onMouseMove)
            map.off('click', onAddDev)
            map.off('contextmenu', stop)
            map.getCanvas().style.cursor = ''
            renderMatchedFeatures(lineGeom)


        }
    }

    function restore() {
        symbolLayer.removeEleDevs()
        clearInterval(intervalId)
        intervalId = null
        map.getSource('cross-water-layer').setData({
            type: "FeatureCollection",
            features: []
        })
        map.getSource('cross-building-layer').setData({
            type: "FeatureCollection",
            features: []
        })
    }

    /**
     * 这里的lineGeom只能是lineString，不能是multiLineString
     * @param lineGeom
     */
    function renderMatchedFeatures(lineGeom) {
        let turf = egisV2.util.TurfUtil
        let features = map.queryRenderedFeatures([[0, 0], [window.innerWidth, window.innerHeight]], {layers: matchedLayers})
        // let features = map.querySourceFeatures('epgis', {sourceLayer: 'Building'})

        let userLine = turf.lineString(lineGeom[0])
        let waterFeatures = []
        let buildingFeatures = []
        features.forEach(item => {
            let targetFill = null
            let isFillExtrusion = false
            if (item.properties.Height) {
                isFillExtrusion = true
            }
            let fillGeom = item.geometry

            let isCross = false

            let isContain = false

            if (fillGeom.type == 'Polygon') {
                targetFill = turf.polygon(fillGeom.coordinates)
                isCross = turf.booleanCrosses(userLine, targetFill)
                isContain = turf.booleanContains(targetFill, userLine)
            } else {
                try {
                    fillGeom.coordinates.forEach(polygonGeom => {
                        if (isCross || isCross) {
                            throw  new Error('匹配')
                        } else {
                            targetFill = turf.polygon(polygonGeom)
                            isCross = turf.booleanCrosses(userLine, targetFill)
                            isContain = turf.booleanContains(targetFill, userLine)
                        }

                    })
                } catch (exp) {
                    console.log('多面匹配结束')
                }

            }


            if (isCross || isContain) {
                if (isFillExtrusion) {

                    let scaledPolygon = turf.transformScale(turf.polygon(item.geometry.coordinates), 1.02)
                    item.geometry = scaledPolygon.geometry
                    // debugger
                    buildingFeatures.push(item)
                } else {
                    waterFeatures.push(item)
                }

            }
        })
        map.getSource('cross-water-layer').setData({
            type: "FeatureCollection",
            features: waterFeatures
        })
        map.getSource('cross-building-layer').setData({
            type: "FeatureCollection",
            features: buildingFeatures
        })
        clearInterval(intervalId)
        intervalId = setInterval(() => {
            defaultOpacity += 0.02 * opacityFlag
            if (defaultOpacity >= 1) {
                opacityFlag = -1
                defaultOpacity = 1
            }
            if (defaultOpacity <= 0) {
                opacityFlag = 1
                defaultOpacity = 0
            }
            map.setPaintProperty('cross-water-layer', 'fill-opacity', defaultOpacity)
            map.setPaintProperty('cross-building-layer', 'fill-extrusion-opacity', defaultOpacity)

        }, 16)
    }

    let defaultOpacity = 1
    let opacityFlag = 1
    let matchedLayers = ['Water', 'Building']
    let intervalId = null

    function initPage() {
        symbolLayer = new egisV2.layer.SymbolLayer(map)
        map.on('moveend', e => {
            if (lineSymbol && intervalId) {
                let lineGeom = lineSymbol.getGeometry()
                renderMatchedFeatures(lineGeom)
            }

        })
        map.addLayer({
            id: 'cross-water-layer',
            type: "fill",
            source: {
                type: "geojson",
                data: {
                    type: "FeatureCollection",
                    features: []
                }
            },
            paint: {
                "fill-outline-color": '#cccccc',
                "fill-color": '#ff00ff',
                "fill-opacity": 0.6
            }
        })

        map.addLayer({
            id: 'cross-building-layer',
            type: "fill-extrusion",
            source: {
                type: "geojson",
                data: {
                    type: "FeatureCollection",
                    features: []
                }
            },
            paint: {
                "fill-extrusion-base": 1,
                "fill-extrusion-color": '#ff00ff',
                "fill-extrusion-height": ["to-number", ["+", 0.02, ['get', 'Height']]],
                // "fill-extrusion-height": ['get','Height'],
                "fill-extrusion-opacity": 1
            }
        })


    }

    window.onload = function () {
        loadGeoMap(initPage)
    }


</script>
</body>
</html>
